package com.neusoft.neu24.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.neusoft.neu24.Result.CommonResult;
import com.neusoft.neu24.Result.ResultCode;
import com.neusoft.neu24.entity.AirEntity;
import com.neusoft.neu24.entity.Province;
import com.neusoft.neu24.entity.StatisticsEntity;
import com.neusoft.neu24.mapper.AirEntityMapper;
import com.neusoft.neu24.mapper.StatisticsEntityMapper;
import com.neusoft.neu24.service.IAirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class AirServiceImpl implements IAirService {

    @Autowired
    private AirEntityMapper airEntityMapper;

    @Autowired
    private StatisticsEntityMapper statisticsEntityMapper;


    @Override
    public CommonResult<Integer> load() {
        List<AirEntity> airList =  airEntityMapper.query();
        if (airList.isEmpty()) return CommonResult.failed(ResultCode.NULL);

        Map<String, String> mapping = new HashMap<>(16);
        mapping.put("fpid", "provinceId");
        mapping.put("fcid", "cityId");
        mapping.put("faddress", "address");
        mapping.put("so2value", "so2Value");
        mapping.put("so2level", "so2Level");
        mapping.put("covalue", "coValue");
        mapping.put("colevel", "coLevel");
        mapping.put("spmvalue", "spmValue");
        mapping.put("spmlevel", "spmLevel");
        mapping.put("aqilevel", "aqiId");
        mapping.put("updatetime", "confirmDate");
        mapping.put("gid", "gmId");
        mapping.put("pid", "fdId");
        mapping.put("remark", "information");

        List<StatisticsEntity> list = BeanUtil.copyToList(airList, StatisticsEntity.class, new CopyOptions().setFieldMapping(mapping));
        if (list.isEmpty()) return CommonResult.failed(ResultCode.NULL);

        if (statisticsEntityMapper.deleteAll() == 0) return CommonResult.failed(ResultCode.DB_ERROR);

        Integer res = statisticsEntityMapper.insertAll(list);
        if (res == 0) return CommonResult.failed(ResultCode.DB_ERROR);

        return CommonResult.success(res);
    }

    @Override
    public CommonResult<Integer> loadProvinces() {
        List<Province> provinces = airEntityMapper.queryProvinces();
        Integer integer = airEntityMapper.insertProvinces(provinces);
        if (integer <= 0) return CommonResult.failed(ResultCode.DB_ERROR);
        return CommonResult.success(integer);
    }
}
